import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout'),
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: () => import ('@/views/home')
      },
      {
        path: 'user-info',
        component: () => import ('@/views/user/UserInfo')
      },
      {
        path: 'user-avatar',
        component: () => import ('@/views/user/UserAvatar')
      },
      {
        path: 'user-pwd',
        component: () => import ('@/views/user/UserPwd')
      },
      {
        path: 'art-cate',
        component: () => import ('@/views/article/ArtCate')
      },
      {
        path: 'art-list',
        component: () => import ('@/views/article/ArtList')
      },
    ]
  },
  {
    path: '/register',
    component: () => import('@/views/register')
  },
  {
    path: '/login',
    component: () => import('@/views/login')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const whiteList = ['/login','/register']

//全局前置路由守卫
router.beforeEach((to, from, next) => {
  const token = store.state.token

  //判断有无登录
  if(token) {
    //登录了
    if(!store.state.userInfo.username) {
      store.dispatch('initUserInfo')
    }
    next()

  } else {

    //includes 数组的方法：判断值是否在数组里出现过，出现过原地返回 true
    //未登录
    if(whiteList.includes(to.path)) {
      next()

    } else {
      next('/login')
    }
  }
  
  
})

export default router
